package com.mycom.common.utils;

import com.mycom.common.wxpay.WdPayBase;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.ConnectionPoolTimeoutException;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.SSLContext;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.net.SocketTimeoutException;
import java.security.KeyStore;

/**
 * create secure connections with a custom SSL
 * context.
 */
public class ClientCustomSSL {
    private static Logger log = LoggerFactory.getLogger(ClientCustomSSL.class);

    public final static void main(String[] args) throws Exception {
        SSLConnectionSocketFactory sslsf = getSslsf(WdPayBase.GuanDan.mch_id, WdPayBase.GuanDan.cert_file_path);
        CloseableHttpClient httpclient = HttpClients.custom()
                .setSSLSocketFactory(sslsf)
                .build();
        try {
            HttpGet httpget = new HttpGet("https://api.mch.weixin.qq.com/secapi/pay/refund");
            System.out.println("executing request" + httpget.getRequestLine());

            CloseableHttpResponse response = httpclient.execute(httpget);
            try {
                HttpEntity entity = response.getEntity();

                System.out.println("----------------------------------------");
                System.out.println(response.getStatusLine());
                if (entity != null) {
                    System.out.println("Response content length: " + entity.getContentLength());
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent()));
                    String text;
                    while ((text = bufferedReader.readLine()) != null) {
                        System.out.println(text);
                    }
                   
                }
                // EntityUtils.toString(entity, "UTF-8");
                EntityUtils.consume(entity);
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
    }

    /**
     * 微信提现
     *
     * @param mch_id
     * @param url
     * @param postDataXML
     * @return
     */
    public static String wxWithdrawalsPost(String mch_id, String cert_file_path, String url, String postDataXML)
            throws Exception {
        String result = null;

        SSLConnectionSocketFactory sslsf = getSslsf(mch_id, cert_file_path);
        StringEntity postEntity = new StringEntity(postDataXML, "UTF-8");

        // httpPost.addHeader("Content-Type", "text/xml");
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(postEntity);

        CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
        log.info("executing request" + httpPost.getRequestLine());
        try {
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            result = EntityUtils.toString(entity, "UTF-8");
        } catch (ConnectionPoolTimeoutException e) {
            log.error("http get throw ConnectionPoolTimeoutException(wait time out) ", e);
        } catch (ConnectTimeoutException e) {
            log.error("http get throw ConnectTimeoutException", e);
        } catch (SocketTimeoutException e) {
            log.error("http get throw SocketTimeoutException", e);
        } catch (Exception e) {
            log.error("http get throw Exception", e);
        } finally {
            httpPost.releaseConnection();
        }

        return result;
    }

    private static SSLConnectionSocketFactory getSslsf(String mch_id, String cert_file_path) throws Exception {
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        FileInputStream instream = new FileInputStream(new File(cert_file_path));
        try {
            keyStore.load(instream, mch_id.toCharArray());
        } finally {
            instream.close();
        }

        // Trust own CA and all self-signed certs
        SSLContext sslcontext = SSLContexts.custom()
                .loadKeyMaterial(keyStore, mch_id.toCharArray())
                .build();
        // Allow TLSv1 protocol only
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                sslcontext,
                new String[]{"TLSv1"},
                null,
                SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);

        return sslsf;
    }
}
